#include <bits/stdc++.h>

#define pb push_back
#define eb emplace_back
#define fi first
#define se second
#define in read<int>()
#define lin read<ll>()
#define rep(i, x, y) for(int i = (x); i <= (y); i++)
#define per(i, x, y) for(int i = (x); i >= (y); i--)

using namespace std;

using ll = long long;
using db = double;
using pii = pair < int, int >;
using vec = vector < int >;
using veg = vector < pii >;

template < typename T > T read() {
	T x = 0; bool f = 0; char ch = getchar();
	while(!isdigit(ch)) f |= ch == '-', ch = getchar();
	while(isdigit(ch)) x = x * 10 + (ch ^ 48), ch = getchar();
	return f ? -x : x;
}

template < typename T > void chkmax(T &x, const T &y) { x = x > y ? x : y; }
template < typename T > void chkmin(T &x, const T &y) { x = x < y ? x : y; }

const int M = 1e4 + 10;
const int N = 1e6 + 10;

int n, d, t, top, al[M], ans, pot[N];

void divide(int x) {
	top = 0;
	rep(i, 2, x) {
		if(i * i > x) break; if(x % i) continue;
		while(x % i == 0) x /= i;
		al[++top] = i; 
	} if(x > 1) al[++top] = x;
}

ll qp(ll x, int t) { ll res = 1; for(; t; t >>= 1, x = x * x % n) if(t & 1) res = res * x % n; return res; }

bool check(int x) {
	rep(i, 1, top) if(qp(x, t / al[i]) == 1) return 0;
	return 1;
}

int phi(int x) {
	int res = x;
	rep(i, 2, x) {
		if(i * i > x) break;
		if(x % i) continue;
		res = res / i * (i - 1);
		while(x % i == 0) x /= i;
	} if(x > 1) res = res / x * (x - 1);
	return res;
}

void solve() {
	n = in, d = in, t = phi(n);
	if(n == 2) {
		puts("1");
		if(d == 1) puts("1");
		else puts("");
		return;
	}
	divide(t); int g = 0;
	rep(i, 2, 40) if(__gcd(i, n) == 1 && check(i)) { g = i; break; }
	ans = 0;
	if(g) {
		rep(i, 1, t - 1) if(__gcd(i, t) == 1) pot[++ans] = qp(g, i);
		sort(pot + 1, pot + ans + 1);
	}
	printf("%d\n", ans);
	rep(i, d, ans) { printf("%d ", pot[i]); i += d - 1; } puts("");
}

int main() {
#ifndef ONLINE_JUDGE
	freopen("1.in", "r", stdin);
#endif
	int T = in; while(T--) solve();	
	return 0;
}
